import re,sys,os,socket
import gzip,os,string,tempfile
from urllib2 import *
from threading import Thread
from Queue import Queue
import time,gzip,tempfile,string,random
from handler import handler

class dmzj_handler(handler):
  def __init__(self):
    handler.__init__(self)
  def extract_url_lst(self,url):
    page=handler.try_to_read_url(self,url)
    page = self.decompress_if_gzip(page)
    page=page.replace("\n","")
    page=page.replace("\r","")
    l = re.findall("<div class=\"cartoon_online_border.*?</div>",page)
    l = "".join(l)
    res = re.findall(" href=\"(.*?)\".*?",l)
    return res
  def download_img(self,url,file_name):
    #  file name here is directory path
    if file_name.endswith(".jpg"):
      file_name=file_name[:file_name.rfind(os.path.sep)]
    if not os.path.exists(file_name):
      os.mkdir(file_name)
    from gallery_downloader import GD
    gd = GD(dmzj_sub_handler(),url,file_name,thread_num=10)
    gd.start_download()

class dmzj_sub_handler(handler):
  def __init__(self):
    handler.__init__(self)

  def extract_url_lst(self,url):
    page = self.try_to_read_url(url)
    page = self.decompress_if_gzip(page)
    exec "l=%s" % re.findall("var pages = '([^']*)'",page)[0]
    lst=[]
    for s in l:
      exec "t=u'%s'" % s
      lst.append(t)
    lst=map(lambda x:"http://manhua.178.com/imgs/"+x.encode('utf-8'),lst)
    lst=map(lambda x:x.replace('\\/','/'),lst)
    lst=map(lambda x:x.replace(' ','%20'),lst)
    return lst

  def download_img(self,url,file_name):
    handler.download_img(self,url,file_name)

  def get_dir_name(self,dir,url):
    if not dir.endswith(os.path.sep):
      dir+=os.path.sep
    page=self.try_to_read_url(url)
    page = self.decompress_if_gzip(page)
    title=re.findall("<title>(.*?)</title>",page)[0].decode('utf-8')
    return dir+title+os.sep
